/**
 * @author Lssong
 * @email 1027820283@qq.com
 * @create date 2021-08-16 16:57:56
 * @modify date 2021-08-16 16:57:56
 * @desc 用户模型
 */
const {sequelize} = require('../../core/db')
const { Sequelize, Model } = require('sequelize')
const bcrypt = require('bcryptjs')

class UserModel extends Model {
  static async verifyEmailPassword(email, plainPassword) {
    // 查询用户
    const user = await UserModel.findOne({
        where: {
            email
        }
    })
    if (!user) {
        throw new global.errs.AuthFailed('账号不存在')
    }
    // console.log(user)
    // console.log(user.dataValues)
    // console.log(plainPassword)
    // 验证密码
    const correct = bcrypt.compareSync(plainPassword, user.dataValues.password)
    if (!correct) {
        throw new global.errs.AuthFailed('密码不正确')
    }
    return user
  }

  /**
   * 查询小程序openid是否存在
   * @param {*} openid 
   */
  static async getUserByOpenid(openid) {
    const user = await UserModel.findOne({
      where: {
        openid
      }
    })
    return user;
  }

  // 注册小程用户
  static async createUserByOpenid(openid) {
    // 查询用户
    const user = await UserModel.create({
        openid
    })

    return user;
  }
}

UserModel.init({
  // 主键名
  id: { 
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  nickname: Sequelize.STRING,
  email: Sequelize.STRING,
  // model的属性操作
  password: { 
    // 扩展 设计模式 观察者模式
    // ES6 Reflect Vue3.0
    type: Sequelize.STRING,
    set(val) {
      const salt = bcrypt.genSaltSync(4)
      const psw = bcrypt.hashSync(val, salt)
      this.setDataValue('password',psw)
    }
  },
  openid: {
    type: Sequelize.STRING(64),
    unique: true
  },
  test: Sequelize.STRING
}, {
   // 这是其他模型参数
   sequelize, // 我们需要传递连接实例
   modelName: 'User' // 我们需要选择模型名称
})


module.exports = {
  UserModel
}